import type {NitroFetchRequest} from "nitropack";
import { ElMessage } from 'element-plus'
interface Params {
    url:NitroFetchRequest;
    params?:Record<string, any>;
    method?:"get" | "post";
    pick?:[];
    headers?:Record<string, any>;
    contentType?:'application/json' | 'multipart/form-data'|'application/x-www-form-urlencoded';
}

let loadingCount = 0;

export async function request({url, params, method = "get", headers = {},pick=[], contentType="application/json"}:Params){
    loadingCount++;
    const { public: { apiBase } } = useRuntimeConfig()
    const {data,refresh,error} = await useFetch(url, {
        method,
        baseURL: apiBase,
        timeout: 10000,
        pick,
        headers: {
            ...headers,
            "Content-Type": contentType,
        },
        /* 请求拦截 */
        onRequest: ({request,options}) => {
            /* 可以再这里设置header token 等 */
            switch (method) {
                case "get":
                    options.query = {...params};
                    break;
                case "post":
                    options.params = {...params};
                    break;
                default:
                    options.body = params;
            }
            loadingCount++;
        },
        /* 响应拦截 */
        onResponse: ({request, response, options}) => {
            loadingCount--;
            /* 处理响应数据 */
            return response;
        },
        onRequestError: ({request, options, error}) => {
            /* 处理请求错误 */
            loadingCount--;
            return ElMessage.error(error);
        },
        onResponseError: ({request, response, options}) => {
            /* 处理响应错误 */
            return ElMessage.error('error!');
        },
    });

    /* 这里data本身是个ref对象,将其内部值抛出去方便调用时获取数据 */
    return data.value;
}